<template>
  <div>
    <h3>自定义指令封装防抖</h3>
    <button v-shake @click="fn">点我</button>

    <div>
      <button v-shake @click="fn2">点我2</button>
    </div>
  </div>
</template>

<script>
export default {
  methods: {
    fn() {
      console.log("aaaa");
    },
    fn2() {
      console.log("bbbbbbbb");
    },
  },
  directives: {
    shake: {
      bind(el, option) {
        let time = null;
        // 设置防抖时间
        if (option.value) {
          time = option.value;
        } else {
          time = 2000;
        }

        let cbFn = null;

        el.addEventListener(
          "click",
          (event) => {
            // 第一次执行
            if (!cbFn) {
              cbFn = setTimeout(() => {
                cbFn = null;
              }, time);
            } else {
              // stopImmediatePropagation  阻止后续的事件进行执行
              event.stopImmediatePropagation();
            }
          },
          true
        );
      },
    },
  },
};
</script>

<style>
</style>